package org.west.sky.frame.activiti.study.chapter18;

import org.activiti.engine.history.HistoricVariableInstance;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.time.DateUtils;
import org.west.sky.frame.activiti.study.chapter18.demo0101.ProcessExecutionListener;
import org.west.sky.frame.activiti.study.chapter18.demo0101.SequenceFlowExecutionListener;
import org.west.sky.frame.activiti.study.chapter18.demo0101.UserTaskExecutionListener;
import org.west.sky.frame.activiti.study.util.ActivitiEngineUtil;

import java.util.HashMap;
import java.util.Map;

/**
 * author: chz
 * date: 2025/6/6
 * description: 执行监听器
 */
public class RunDemo18_1_1 extends ActivitiEngineUtil {

    public static void main(String[] args) {
        RunDemo18_1_1 runDemo18_1_1 = new RunDemo18_1_1();
        runDemo18_1_1.run();
    }

    public void run() {
        // 启动流程
        loadActivitiConfigAndInitEngine();
        ProcessDefinition processDefinition = deployByClassPathResource("processes/chapter18/Chapter18_1_1.bpmn20.xml");

        Map<String ,Object> variables = new HashMap<>();
        variables.put("processExecutionListener", new ProcessExecutionListener());
        variables.put("sequenceFlowExecutionListener", new SequenceFlowExecutionListener());
        variables.put("userTaskExecutionListener", new UserTaskExecutionListener());
        variables.put("nowTime1", "时间1");

        ProcessInstance processInstance = runtimeService.startProcessInstanceById(processDefinition.getId() ,variables);

        System.out.println("====流程实例ID：" + processInstance.getId());

        Task task = taskService.createTaskQuery().processInstanceId(processInstance.getId()).singleResult();
        System.out.println("====第一个任务id:" + task.getId() + ",任务名称：" + task.getName());
        Map<String ,Object> variables2 = new HashMap<>();
        variables2.put("nowTime2", "时间2");
        taskService.complete(task.getId(), variables2);

        for (HistoricVariableInstance instance : historyService.createHistoricVariableInstanceQuery().processInstanceId(processInstance.getId()).list()) {
            System.out.println("====变量：" + instance.getVariableName() + "的值为：" + instance.getValue());
        }

        closeEngine();
    }
}
